package net.bjtelecom.cacs.servlet;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; 

/**
 * Servlet Filter implementation class AuthFilter
 */
public class AuthFilter implements Filter {

	String LOGIN_PAGE="/CrmAutoConfigSys/login.jsp"; 
	protected FilterConfig filterConfig; 
    /**
     * Default constructor. 
     */
    public AuthFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
		this.filterConfig=null; 
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		HttpServletRequest hreq = (HttpServletRequest)request; 
		HttpServletResponse hres = (HttpServletResponse)response;
		String currentURL = hreq.getRequestURI();
		String targetURL = currentURL.substring(currentURL.indexOf("/",1));
		// pass the request along the filter chain
		if ( !targetURL.equals("/login.jsp")){
			String isLog=(String)hreq.getSession().getAttribute("isLog"); 
			if((isLog!=null)&&((isLog.equals("true"))||(isLog=="true"))){
				chain.doFilter(request, response);
				return;
			}else
			{
				hres.sendRedirect(LOGIN_PAGE);
				return;
			}
		}else{
			chain.doFilter(request, response);
			return;
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		this.filterConfig=fConfig; 
	}
	
	public void setFilterConfig(final FilterConfig filterConfig){ 
	    this.filterConfig=filterConfig; 
	}  

}
